import { createIntl, createIntlCache } from "react-intl";
import enMessages from "../locales/en.json";
import zhMessages from "../locales/zh.json";

const cache = createIntlCache();
let currentLocale = localStorage.getItem("locale") || "zh";

console.log("执行多语言逻辑", currentLocale);

const messages = {
  en: enMessages,
  zh: zhMessages,
};

const intl = createIntl(
  {
    locale: currentLocale,
    messages: messages[currentLocale],
  },
  cache
);

export function getLocal() {
  return intl.locale;
}

export function updateLanguage(newLocale) {
  currentLocale = newLocale;
  intl.locale = newLocale;
  intl.messages = messages[newLocale];
  localStorage.setItem("locale", newLocale);
  location.reload();
}

export const T = function (defaultMessage, id, param = {}) {
  return intl.formatMessage({ id, defaultMessage }, param);
};

export default T;
